package com.china08.yxyapi.api.manage.tec.teaching.lecture.res;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.YxyResUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

import io.swagger.annotations.ApiOperation;

/**
 * 老师 ---备授课--备课资源查询
 * 
 */
@CrossOrigin
@RestController
public class LectureSrhResController extends YxyApiBaseController {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private YxyResUtil YxyResUtil;

    @Value("${yxy.res.url}")
    private String yxy_res_url;

    @Autowired
    private MongoTemplate mt;

    @ApiOperation(value = "备课资源查询")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/res/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req) {

        String userId = getProfile(request, response).getId();
        String schoolId = getProfile(request, response).getSchoolId();
        String userVip = getProfile(request, response).getResVip();
        Assert.notNull(StringUtils.defaultIfBlank(userId, null), "用户id必须");
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "学校id必须");

        Pageable pageable = req.getPageable(Direction.DESC, "createdDate");

        List<Integer> sList = new ArrayList<Integer>();
        sList.add(1);
        DBObject dbObject = new BasicDBObject();
        // 基本条件
        dbObject.put("userId", userId);
        dbObject.put("schoolId", schoolId);
        dbObject.put("bookcontentsId", req.bookcontentsId);
        dbObject.put("isDelete", 0);
        // 筛选条件
        if (StringUtils.isBlank(req.keyword)) {
            if (StringUtils.isNotBlank(req.typeId)) {
                if (req.typeId.equals("jl04")) {
                    dbObject.put("typeId", req.typeId);
                    BasicDBObject in = new BasicDBObject("$nin", sList);
                    dbObject.put("resType", in);
                } else {
                    dbObject.put("typeId", req.typeId);
                }
            }
        } else {
            if (StringUtils.isBlank(req.typeId)) {
                Pattern queryPattern = Pattern.compile(req.keyword, Pattern.CASE_INSENSITIVE);
                dbObject.put("resName", queryPattern);
            } else {
                if (req.typeId.equals("jl04")) {
                    dbObject.put("typeId", req.typeId);
                    BasicDBObject in = new BasicDBObject("$nin", sList);
                    dbObject.put("resType", in);
                    Pattern queryPattern = Pattern.compile(req.keyword, Pattern.CASE_INSENSITIVE);
                    dbObject.put("resName", queryPattern);
                } else {
                    dbObject.put("typeId", req.typeId);
                    Pattern queryPattern = Pattern.compile(req.keyword, Pattern.CASE_INSENSITIVE);
                    dbObject.put("resName", queryPattern);
                }

            }
        }

        // 返回字段
        BasicDBObject fieldsObject = new BasicDBObject();
        fieldsObject.put("id", true);
        fieldsObject.put("resourceId", true);
        fieldsObject.put("formatId", true);
        fieldsObject.put("resName", true);
        fieldsObject.put("resType", true);
        fieldsObject.put("quesIds", true);
        fieldsObject.put("resUploader", true);
        fieldsObject.put("createdDate", true);
        fieldsObject.put("fileSize", true);

        Query query = new BasicQuery(dbObject, fieldsObject);

        // 总数
        long total = 0l;
        total = mt.count(query, YxyLectureRes.class);

        // 排序
        query.with(pageable);
        // 分页
        query.skip((pageable.getPageNumber()) * pageable.getPageSize()).limit(pageable.getPageSize());
        List<YxyLectureRes> list = null;
        list = mt.find(query, YxyLectureRes.class);
        Assert.isTrue(null != list, "资源为空");

        String schoolNick = getProfile(request, response).getSchoolName();
        List<RespModel> respModels = new ArrayList<RespModel>();
        if (list != null) {
            RespModel respModel = null;
            for (YxyLectureRes res : list) {
                GetQuery getQuery = new GetQuery();
                getQuery.setId(res.getResourceId());
                ElasticYxyResResource elasticYxyResResource = elasticsearchTemplate.queryForObject(getQuery,
                        ElasticYxyResResource.class);
                respModel = new RespModel();
                respModel.userVip = userVip;
                respModel.qid = res.getId();
                respModel.id = res.getResourceId();
                if (null != res.getResourceId()) {
                    if (null != elasticYxyResResource) {
                        respModel.vip = elasticYxyResResource.getIsVip();
                        respModel.isHighQualityYx = elasticYxyResResource.getIsHighQualityYx();
                    }
                } else {
                    respModel.vip = false;
                    respModel.isHighQualityYx = 0;
                }
                respModel.quesGroupId = res.getId();
                respModel.formatId = res.getFormatId();
                Integer fileSize = res.getFileSize();
                if (null != fileSize) {
                    Double valueOf = Double.valueOf(fileSize + "");
                    Double file = valueOf / 1024;
                    BigDecimal bg = new BigDecimal(file);
                    double f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                    respModel.fileSize = f1;
                } else {
                    respModel.fileSize = 0;

                }
                if (res.getResType() == 2) {
                    respModel.schoolNick = schoolNick;
                } else {
                    respModel.schoolNick = elasticYxyResResource != null ? elasticYxyResResource.getUploaderSchoolName()
                            : "云校";
                }

                respModel.author = res.getResUploader();
                respModel.dateFormat = DateToolUtils.format(res.getCreatedDate(), DateToolUtils.FORMAT_SHORT_YMD);
                respModel.title = res.getResName();
                respModel.resType = res.getResType();
                respModel.quesIds = res.getQuesIds();
                // 资源下载
                String download = YxyResUtil.getDownloadUrl(respModel.id);
                respModel.downloadLocation = download;
                respModel.preview = YxyResUtil.getPreviewUrl(respModel.id);
                if (schoolId.equals("ff80808142a16af00142a1a60f010006")
                        || "ff80808142a16af00142a1a60f010006".equals(res.getSchoolId())) {
                    respModel.schoolNick = "";
                }
                respModels.add(respModel);
            }
        }

        Page<RespModel> pageRes = new PageImpl<RespModel>(respModels, pageable, total);

        return pageRes;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String bookcontentsId;
        public String keyword;
        public String typeId;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(bookcontentsId, null), "目录节点不能为空!");
        }

    }

    protected static class RespModel extends YxyApiRespModel {
        public String qid;//
        public String id;//
        public String formatId;
        public String title;
        public String quesGroupId;//
        public Integer resType;
        public List<String> quesIds;
        public String schoolNick;//
        // 资源的拥有者
        public String author;
        // 收录时间
        public String dateFormat;
        // 下载连接
        public String downloadLocation = "";//
        // 资源大小
        public double fileSize;
        // 预览
        public String preview = "";//
        // 是否是VIP
        public boolean vip;//
        // 是否为精品资源
        public Integer isHighQualityYx;//
        // 用户是否为VIP
        public String userVip;//
    }
}
